package com.shop.cereshop.admin.job;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.shop.cereshop.admin.dao.buyer.CereBuyerUserDAO;
import com.shop.cereshop.admin.dao.disable.BuyerDisableTimeDAO;
import com.shop.cereshop.admin.page.user.BuyerUsersVO;
import com.shop.cereshop.admin.service.buyer.CereBuyerUserService;
import com.shop.cereshop.commons.domain.disable.BuyerDisableTime;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Order(11)
@Slf4j
public class UserDisableTime {

    @Autowired
  private   BuyerDisableTimeDAO buyerDisableTimeDAO;

    @Autowired
    private CereBuyerUserDAO cereBuyerUserDAO;
    @XxlJob("userDisableTime")
    @Scheduled(cron = "0 0/1 * * * ?")// 每 3分钟执行一次
//    定时修改用户封禁时间是否过期
    @Transactional
    public void userDisableTime() {
        log.info("开始删除用户封禁时间已结束禁言的数据");
//        获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
//        将当前时间转换成时间戳的形式
        Long nowTime = currentTime.toInstant(java.time.ZoneOffset.of("+8")).toEpochMilli();
//            从封禁时间表中获取所有的封禁时间
        List<BuyerDisableTime> buyerDisableTimes = buyerDisableTimeDAO.selectDisableTime();
//        取出用户id和禁言时长
        if (CollectionUtils.isNotEmpty(buyerDisableTimes)) {
            HashMap<Long, Long> userIdAndBanTime = new HashMap<>();
            for (BuyerDisableTime buyerDisableTime : buyerDisableTimes) {
                Long userId = buyerDisableTime.getBuyerId();
                Long banTime = buyerDisableTime.getDisableTime().toInstant(java.time.ZoneOffset.of("+8")).toEpochMilli();
                userIdAndBanTime.put(userId, banTime);
            }
//首先过滤出用户封禁时间小于当前时间的用户id
            List<Long> userIds = userIdAndBanTime.entrySet().stream()
                    .filter(entry -> entry.getValue() < nowTime)
                    .map(entry -> entry.getKey())
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(userIds)) {
//            批量更新用户的状态
                Integer i = cereBuyerUserDAO.updateStateList(userIds);
//                批量删除用户封禁数据
                int h = buyerDisableTimeDAO.deleteBatchBuyerIds(userIds);
                if (h > 0){
                    log.info("删除了{}个用户封禁数据", h);
                }else {
                    log.info("没有需要删除的封禁数据");
                }

                if (i > 0) {
                    log.info("解封了{}个用户", i);
                } else {
                    log.info("没有需要解封的用户");
                }
            }
        }
        log.info("结束删除用户封禁时间已结束禁言的数据");
    }
}
